import React from 'react';
import { Form, Table, Button, message, Modal, Popover, Input } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import IconButton from '@/components/IconButton';
import FormulaExpression from '@/components/FormulaExpression';

const FormItem = Form.Item;
@connect(({ loading }) => ({
  loading: loading.effects['product/fetchCalcRules'] || loading.effects['service/fetchCalcRules'],
  confirmLoading: loading.effects['product/validCalcRule'],
}))
@Form.create()
class WeightRuleTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      ruleList: [],
      tempRulist: [],
      modalVisible: false,
      conditionValueText: '',
      conditionVisible: false,
      ruleValueText: '',
      ruleVisible: false,
      update: {
        isUpdate: false,
        idx: 999,
      },
    };
  }
  columns = [
    {
      title: '条件',
      dataIndex: 'conditionStr',
      width: '40%',
      editable: true,
    },
    {
      title: '规则',
      dataIndex: 'resultStr',
      width: '40%',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record, index) => {
        return (
          <>
            <IconButton title="编辑" icon="icon-edit" onClick={() => this.edit(record, index)} />
            <IconButton title="删除" icon="icon-delete" onClick={() => this.delete(index)} style={{ marginLeft: 10 }}/>
          </>
        );
      },
    },
  ];
  componentDidMount() {
    this.getProductOrServiceRule();
  }
  componentWillUnmount() {
    const { onSave } = this.props;
    const { tempRulist } = this.state;
    onSave(tempRulist);
  }

  getProductOrServiceRule = () => {
    const { serviceId, type, productId } = this.props;
    let id = '';
    if (type === 'isProduct') {
      id = productId;
    } else {
      id = serviceId;
    }
    this.getCalcRules(id);
  };

  getCalcRules = id => {
    const { dispatch, type } = this.props;
    let params = {};
    if (type === 'isProduct') {
      params = {
        type: 'product/fetchCalcRules',
        payload: {
          pathParams: {
            productId: id,
          },
        },
      };
    } else {
      params = {
        type: 'service/fetchCalcRules',
        payload: {
          pathParams: {
            serviceId: id,
          },
        },
      };
    }
    dispatch(params).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        this.setState({
          ruleList: data,
          tempRulist: data,
        });
      }
    });
  };

  delete = index => {
    const { onSave } = this.props;
    Modal.confirm({
      title: '删除体积计费重规则',
      content: '确定删除此体积计费重规则吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const { ruleList } = this.state;
        let operatList = _.cloneDeep(ruleList);
        operatList.splice(index, 1);
        this.setState({
          ruleList: operatList,
        }, () => {
          message.success('删除成功');
        });
        onSave(operatList);
      },
    });
  };

  edit = (record, index) => {
    const { conditionStr, resultStr } = record;
    const { form } = this.props;
    this.setState(
      {
        modalVisible: true,
        update: {
          isUpdate: true,
          idx: index,
        },
        conditionValueText: conditionStr,
        ruleValueText: resultStr,
      },
      () => {
        form.setFieldsValue({ conditionStr });
        form.setFieldsValue({ resultStr });
      }
    );
  };

  handleAdd = () => {
    this.setState({
      modalVisible: true,
    });
  };

  handleCheckValidity = () => {
    const { form, dispatch, onSave } = this.props;
    const { ruleList, update } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'product/validCalcRule',
        payload: {
          data: {
            ...fieldsValue,
          },
        },
      }).then(({ errorCode }) => {
        if (errorCode === 0) {
          let newRuleList = [];
          if (update.isUpdate) {
            newRuleList = [...ruleList];
            newRuleList[update.idx] = fieldsValue;
          } else {
            newRuleList = [...ruleList, fieldsValue];
          }
          onSave(newRuleList);
          this.setState({
            conditionValueText: '',
            ruleValueText: '',
            modalVisible: false,
            ruleList: newRuleList,
            update: {
              isUpdate: false,
              idx: 999,
            },
          }, () => {
            message.success('保存成功');
          });
        }
      });
    });
  };
  handleCancelCheck = () => {
    this.setState({
      modalVisible: false,
      conditionValueText: '',
      ruleValueText: '',
      update: {
        isUpdate: false,
        idx: 999,
      },
    });
  };

  handleSetValueText = (val, isConditon = true) => {
    const { form } = this.props;
    if (isConditon) {
      form.setFieldsValue({ conditionStr: val });
      this.setState({
        conditionVisible: false,
        conditionValueText: val,
      });
    } else {
      form.setFieldsValue({ resultStr: val });
      this.setState({
        ruleVisible: false,
        ruleValueText: val,
      });
    }
  };

  handleVisibleChange = (val, isConditon = true) => {
    isConditon ? this.setState({ conditionVisible: val }) : this.setState({ ruleVisible: val });
  };

  renderModal = () => {
    const {
      conditionVisible,
      ruleVisible,
      modalVisible,
      conditionValueText,
      ruleValueText,
    } = this.state;
    const { form, confirmLoading } = this.props;
    const conditionContent = (
      <FormulaExpression maxLength={50} equalClick={this.handleSetValueText} />
    );
    const ruleContent = (
      <FormulaExpression
        maxLength={50}
        isCondition={false}
        equalClick={val => this.handleSetValueText(val, false)}
      />
    );
    return (
      <Modal
        maskClosable={false}
        destroyOnClose
        title="添加计费重规则"
        visible={modalVisible}
        onOk={this.handleCheckValidity}
        onCancel={this.handleCancelCheck}
        confirmLoading={confirmLoading}
      >
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="条件">
          {form.getFieldDecorator('conditionStr', {
            rules: [{ required: true, message: '请设置条件', whitespace: true }],
          })(
            <Popover
              visible={conditionVisible}
              content={conditionContent}
              placement="bottomLeft"
              trigger="click"
              onVisibleChange={this.handleVisibleChange}
            >
              <Input readOnly placeholder="请单击设置条件" value={conditionValueText} />
            </Popover>
          )}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="规则">
          {form.getFieldDecorator('resultStr', {
            rules: [{ required: true, message: '请设置规则', whitespace: true }],
          })(
            <Popover
              visible={ruleVisible}
              content={ruleContent}
              placement="bottomLeft"
              trigger="click"
              onVisibleChange={val => this.handleVisibleChange(val, false)}
            >
              <Input readOnly placeholder="请单击设置规则" value={ruleValueText} />
            </Popover>
          )}
        </FormItem>
      </Modal>
    );
  };

  render() {
    const { ruleList } = this.state;
    const { loading } = this.props;
    return (
      <>
        <IconButton title="添加计费重规则" icon="icon-add" onClick={this.handleAdd} style={{ marginBottom: 20 }}/>
        <Table
          rowKey={record => record.index}
          bordered
          dataSource={ruleList}
          columns={this.columns}
          pagination={false}
          loading={loading}
        />
        {this.renderModal()}
      </>
    );
  }
}

export default WeightRuleTable;
